﻿using System;

namespace FileCloud.NET
{
    /// <summary>
    /// Example of using service API.
    /// </summary>
    public class FileCloudUploader
    {
        #region Constructor

        /// <summary>
        /// Create 
        /// </summary>
        public FileCloudUploader(string username, string password)
        {
            if (String.IsNullOrEmpty(username))
                throw new ArgumentException("username is null or empty.", "username");
            if (String.IsNullOrEmpty(password))
                throw new ArgumentException("password is null or empty.", "password");

            _apiKey = FileCloudAPIWrapper.FetchApiKey(username, password);
        }

        #endregion

        #region Public methods
        
        /// <summary>
        /// Upload file to service.
        /// </summary>
        /// <param name="filepath">Path to file.</param>
        /// <returns>File url, not for direct download.</returns>
        public string Upload(string filepath)
        {
            if (String.IsNullOrEmpty(filepath))
                throw new ArgumentException("filepath is null or empty.", "filepath");

            var uKey = FileCloudAPIWrapper.Uploading(filepath, _apiKey);
            return GetFileUrl(uKey);
        }

        /// <summary>
        /// Upload file to service.
        /// If username and password are null - file will be uploaded as public.
        /// </summary>
        /// <param name="filepath">Path to file.</param>
        /// <param name="username">Username.</param>
        /// <param name="password">Password.</param>
        /// <returns>File url, not for direct download.</returns>
        public static string Upload(string username, string password, string filepath)
        {
            if (String.IsNullOrEmpty(filepath))
                throw new ArgumentException("filepath is null or empty.", "filepath");

            // First you need to get api key for user.
            var apiKey = String.IsNullOrEmpty(username) && String.IsNullOrEmpty(password) ?
                null : FileCloudAPIWrapper.FetchApiKey(username, password);

            // Then you can download file.
            var uKey = FileCloudAPIWrapper.Uploading(filepath, apiKey);

            // We can convert file key to url.
            return GetFileUrl(uKey);
        }

        /// <summary>
        /// Convert fileKey to file Url.
        /// </summary>
        /// <param name="fileKey">The unique key for a file.</param>
        /// <returns>File url.</returns>
        public static string GetFileUrl(string fileKey)
        {
            return string.Format(FILE_URL_FORMAT, fileKey);
        }

        #endregion

        #region Private members

        private const string FILE_URL_FORMAT = @"http://filecloud.io/{0}";

        private string _apiKey;

        #endregion
    }
}
